﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LoomDataEmulator.Data;
using System.Threading;

namespace LoomDataEmulator.Core
{
    public class CmiDaiInputProcessor : IInputProcessor, IOutputProcessor, IScheduledTask
    {
        private List<FileMetaData> _fileMetaDataList;
        private bool _registered;

        public List<FileMetaData> FileMetaDataList
        {
            get { return _fileMetaDataList; }
            set { _fileMetaDataList = value; }
        }
        #region IProcessInput Members

        public CmiDaiInputProcessor()
        {
            if (FileMetaDataList == null)
                FileMetaDataList = new List<FileMetaData>();
        }

        public void ProcessInput(object sender, EventArgs e)
        {
            try
            {
                Thread.Sleep(6000);

                FileSystemEventArgs fileSystem = (FileSystemEventArgs)e;
                FileInfo fileCMI = new FileInfo(fileSystem.FullPath);
                FileInfo fileDAI = new FileInfo(fileSystem.FullPath.Replace(".cmi", ".dai"));
                StreamReader readerCMI, readerDAI;
                
                string line = null;
                string[] splittedLine;
                var metaData = new FileMetaData();

                using (readerCMI = new StreamReader(fileCMI.OpenRead()))
                {
                    while (!readerCMI.EndOfStream)
                    {
                        line = readerCMI.ReadLine();

                        if (line.StartsWith("SqlStatement"))
                        {
                            splittedLine = line.Split(' ');

                            string[] type_table = splittedLine[1].Split('_');
                            metaData.CommandType = type_table[1].ToString();
                            metaData.Table.Name = String.Format("ODB_{0}", type_table[2].ToString());
                            metaData.TableFields = splittedLine[2].Replace('%', ' ').Replace(",null", " ");

                            using (readerDAI = new StreamReader(fileDAI.OpenRead()))
                            {
                                while (!readerDAI.EndOfStream)
                                {
                                    metaData.FieldsValue.Add(readerDAI.ReadLine().Replace('\"', '\'').Replace(" AM", ":00").Replace(" PM", ":00"));
                                }
                                readerDAI.Close();
                                fileDAI.Delete();
                                fileDAI = null;
                            }
                        }
                    }

                    readerCMI.Close();
                    fileCMI.Delete();
                    fileCMI = null;
                }

                this._fileMetaDataList.Add(metaData);
           
            }
            catch (Exception err)
            {
                System.Console.WriteLine(err.Message);
            }

        } 

        public void ProcessInput()
        {
            throw new NotImplementedException();
        }

        public void ProcessOutput(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        public void ProcessOutput()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IScheduledTask Members

        public System.Timers.TimersDescriptionAttribute TimersDescriptionAttribute
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Registered
        {
            get { return _registered; }
            set { _registered = value; }
        }

        public void OnElapsedTime(object sender, System.Timers.ElapsedEventArgs e)
        {
            if(_fileMetaDataList.Count > 0)
            {
                Console.WriteLine(String.Format("processing file input count {0}", _fileMetaDataList.Count));

                foreach (var fileMetaData in FileMetaDataList)
                {
                    ProcessInDatabase(fileMetaData);
                }

                _fileMetaDataList.Clear();
            }
        }

        private void ProcessInDatabase(FileMetaData fileMetaData)
        {
            try
            {
                var sqlHandler = new SQLHandler(); //TODO implements disposable

                sqlHandler.DataBaseName = "loomdataemulator"; //TODO get it from app settings
                sqlHandler.DataSource = "."; //TODO get this from app settings
                sqlHandler.IntegratedSecurity = true;

                sqlHandler.Connect();

                switch(fileMetaData.CommandType)
                {
                    case "IoU":
                        sqlHandler.write(fileMetaData);
                        break;
                    case "Del":
                        break;
                }


            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
